import * as React from 'react';
import * as ReactDOM from 'react-dom';

// var jQuery = require("../../bower_components/jquery-2.1.4.min/index.js");
var jQuery = require("jquery");
var WebUploader = require("webUploader");
//window.jQuery = jQuery;
// var WebUploader = require("../../components/upload/webuploader.js");

var IMAGE = require("./imageup.js").IMAGE;
//var VALIDE = require("./valide.js").VALIDE;

//var uploader = require("imports?$=jquery,define=>falseconfig=>{size:50}!../../components/upload/webuploader.js");

var UPIMGAE = React.createClass({

    getInitialState: function() {
        return {
            value: '',
            showIconImage: {},
            uploader: {}
        };
    },
    handleOn: function() {

    },
    changState: function(value) {
        return this.setState(value)
    },
    getState: function(value) {
        return this.state[value]
    },
    componentWillMount: function() {
        var $showImages = {},
            $value, temp = {},
            $img, defaultParam = {
                name: "",
                src: "http://7qn8hl.com1.z0.glb.clouddn.com/",
                status: "done",
                showTop: true,
                id: 0,
                isServerImg: true,
                response: ""
            };
        // var com
        if (this.props.defaultValue != "") {
            $img = this.props.defaultValue.split(";");
            for (var i = 0; i < $img.length; i++) {
                temp = Object.create(defaultParam);
                temp.src += $img[i];
                temp.id = i;
                temp.response = $img[i];
                $showImages[i] = temp;
                //$value.push()
            }

            /*this.props.setFormValue({"name":this.props.name,"value":this.props.defaultValue});
                 //this.props.handleBlur(this.state.value)
                 //console.log(".....................")
                 this.changState({
                 "showIconImage":$showImages
                 })*/

            this.props.setFormValue({
                "name": this.props.name,
                "value": $img
            });
            this.props.handleBlur($img.length < 1 ? "" : $img);
            this.changState({
                "showIconImage": $showImages
            })
            //console.log("上传成功..............")

        }


        /* for(key in showIconImage){
             if(showIconImage[key].response){
             temp.push(showIconImage[key].response)
             }

             }
             this.props.setFormValue({"name":this.props.name,"value":temp});
             */
        /*
             if(this.props.defaultValue instanceof Array){

             }*/
    },
    componentDidMount: function() {

        var $parent = $(ReactDOM.findDOMNode(this));

        var uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: '/components/upload/Uploader.swf',

            // 文件接收服务端。
            server: '/api/caigou/common/upload',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: $(".picture-add", $parent),

            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            compress: {
                width: 1024,
                height: 1024,
                quality: 70
            },
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png,doc,docx',
                mimeTypes: 'image/*,application/msword'
            },
            compress: {
                width: 1024,
                height: 1024,
            }
        });
        this.setState({
            uploader: uploader
        });

        var showIconImage = this.state.showIconImage;
        // var setState = this.changState;
        // 当有文件添加进来的时候
        uploader.on('fileQueued', function(file) {
            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader.makeThumb(file, function(error, src) {

                showIconImage[file.id] = {
                    name: file.name,
                    src: src,
                    status: "loading",
                    showTop: true,
                    id: file.id
                };
                if (error) {
                    showIconImage[file.id] = {
                        name: file.name,
                        src: false,
                        status: "loading",
                        showTop: true,
                        id: file.id
                    };
                }
                //console.log(JSON.stringify(showIconImage))
                this.changState({
                    "showIconImage": showIconImage
                });
            }.bind(this), 144, 144);
        }.bind(this));

        uploader.on('uploadSuccess', function(file, response) {
            var key, temp = [];
            if (response && response.resultCode == "0") {
                showIconImage[file.id]["status"] = "done";
                showIconImage[file.id]["showTop"] = false;
                showIconImage[file.id]["response"] = response.result;
                for (key in showIconImage) {
                    if (showIconImage[key].response) {
                        temp.push(showIconImage[key].response)
                    }

                }
                this.props.setFormValue({
                    "name": this.props.name,
                    "value": temp
                });
                this.props.handleBlur(temp.length < 1 ? "" : temp);

                this.changState({
                    "showIconImage": showIconImage
                })
                //console.log("上传成功..............")
            }

        }.bind(this));
    },
    handleChange: function() {

    },
    removeFile: function(file) {

        var showIconImage = this.state.showIconImage,
            key, temp = [];
        //console.log("删除一个对象")
        file.isServerImg || this.state.uploader.removeFile(file.id);
        delete showIconImage[file.id];
        for (key in showIconImage) {
            if (showIconImage[key].response) {
                temp.push(showIconImage[key].response)
            }

        }
        this.props.setFormValue({
            "name": this.props.name,
            "value": temp
        });
        this.props.handleBlur(temp.length < 1 ? "" : temp);
        this.setState({
            "showIconImage": showIconImage
        })

    },
    handleBlur: function() {
        //console.log("失去焦点")
        this.props.handleBlur(this.state.value)
    },
    render: function() {
        var value = this.state.value;
        var iamges = [];
        for (var key in this.state.showIconImage) {
            iamges.push(<IMAGE removeFile={this.removeFile} showIconImage={this.state.showIconImage[key]} key={key} handleOn={this.handleOn}
                                   uploader={this.state.uploader} changState={this.changState} getState={this.getState}/>)
        }
        iamges.reverse();

        return (
            <div className="from-in-picture">
                    {iamges}
                    <div className="picture-add iconfont icon-tablebuttonadd" id="uploader">
                    </div>
                </div>
        )
    }
})


module.exports = {
    UPIMGAE: UPIMGAE
}


/*


 <div className="from-in-picture">
 <div className="picture-show">
 <div className="show-image"><img src="/images/001.png"/></div>
 <div className="show-title">上传中...</div>
 <div className="show-mark"></div>
 </div>
 <div className="picture-show">
 <div className="show-image"><img src="/images/001.png"/></div>
 <div className="show-title"><span className="icon-del-img-none"></span>完成<span className="icon icon icon-del-img"></span></div>
 <div className="show-mark"></div>
 </div>
 <div className="picture-show">
 <div className="show-image"><img src="/images/001.png"/></div>
 </div>
 <div className="picture-show">
 <div className="show-image"><span className="center-middle">不能预览</span></div>
 </div>
 */
/*  var uploader = WebUploader.create({
 // 选完文件后，是否自动上传。
 auto: true,
 // swf文件路径
 swf: '/components/upload/Uploader.swf',

 // 文件接收服务端。
 server: 'http://webuploader.duapp.com/server/fileupload.php',

 // 选择文件的按钮。可选。
 // 内部根据当前运行是创建，可能是input元素，也可能是flash.
 pick: '#uploader',

 // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
 resize: false,
 // 只允许选择图片文件。
 accept: {
 title: 'Images',
 extensions: 'gif,jpg,jpeg,bmp,png',
 mimeTypes: 'image/*'
 }
 });*/